package service;

import JDBC.DBUtils;
import method.Encryption;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * this class enables user to change password
 */
public class ChangeCode extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        HttpSession session=req.getSession();
        String PhoneNumber=(String)session.getAttribute("PhoneNumber");
        String OldPassword=req.getParameter("OldPassword");
        String NewPassword=req.getParameter("NewPassword");
        String oldPassword ="";
        String newPassword ="";
        try {
            oldPassword = Encryption.aesDecodeStr(OldPassword,"wwwwwwwwwwwwwww1wwwwwwwwwwwwwww1");
            newPassword = Encryption.aesDecodeStr(NewPassword,"wwwwwwwwwwwwwww1wwwwwwwwwwwwwww1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String answer= DBUtils.check(PhoneNumber,oldPassword);
        boolean state=false;
        System.out.println(answer);
        if("true".equals(answer)){
            state=DBUtils.ChangeCode(PhoneNumber,newPassword);
        }
        String str ="{\"answer\":\""+state+"\"}";
        PrintWriter out = resp.getWriter();
        out.println(str);
        out.flush();
        out.close();
    }
}
